//
//  NetworkPermissionManager.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/27.
//

import Network

class NetworkPermissionManager {
    static let shared = NetworkPermissionManager()
    private let monitor = NWPathMonitor()
    private let queue = DispatchQueue(label: "NetworkMonitor")
    
    var isNetworkPermissionGranted: Bool = true
    private var firstUpdateHandled = false
    
    private init() {
        startMonitoring()
    }
    
    func startMonitoring() {
        monitor.pathUpdateHandler = { [weak self] path in
            DispatchQueue.main.async {
                // 检查网络接口是否可用
                if path.availableInterfaces.isEmpty {
                    // 没有可用的网络接口，可能是权限被关闭
                    self?.isNetworkPermissionGranted = false
                } else {
                    // 有可用的网络接口
                    self?.isNetworkPermissionGranted = path.status == .satisfied
                }
            }
        }
        monitor.start(queue: queue)
    }
    
    func startMonitoring(_ completion: ((Bool) -> Void)?) {
        firstUpdateHandled = false
        
        monitor.pathUpdateHandler = { [weak self] path in
            guard let self = self else { return }
            
            DispatchQueue.main.async {
                // 跳过第一次的立即回调
                if LYUserDefaults.shared.getBool(forKey: allowNetworkKey) == nil {
                    LYUserDefaults.shared.setBool(true, forKey: allowNetworkKey)
                    return
                }
                
                // 检查网络状态
                let isAvailable = !path.availableInterfaces.isEmpty && path.status == .satisfied
                completion?(isAvailable)
            }
        }
        
        monitor.start(queue: queue)
    }
    
    func stopMonitoring() {
        monitor.cancel()
    }
}
